package edu.dayu.config;

import edu.dayu.db.DynamicDataSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                String uri = request.getRequestURI();
                String[] split = uri.split("/");
                if ("test".equals(split[1]))
                    DynamicDataSource.setDataSource("primary");
                DynamicDataSource.setDataSource(split[1]);
                return true;
            }
        }).addPathPatterns("/**");
    }
}
